package com.atguigu.gmall.realtime.utils;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtil {


    public static <T> List<T> queryList(Connection connection, String querySql, Class<T> clz, boolean underScoreToCamel) throws Exception {

        //创建集合用于存放结果数据
        ArrayList<T> list = new ArrayList<>();

        //编译SQL
        PreparedStatement preparedStatement = connection.prepareStatement(querySql);

        //执行查询
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        //遍历查询结果,将每行数据转换为T对象放入集合
        while (resultSet.next()) {
            //构建T对象
            T t = clz.newInstance();

            //遍历列
            for (int i = 0; i < columnCount; i++) {
                //获取列名和数据
                String columnName = metaData.getColumnName(i + 1);
//                resultSet.getObject(i + 1);
                Object value = resultSet.getObject(columnName);

                if (underScoreToCamel) {
                    columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
                }

                BeanUtils.setProperty(t, columnName, value);
            }

            //将封装好的T对象添加至集合
            list.add(t);
        }

        //释放资源
        resultSet.close();
        preparedStatement.close();

        //返回集合
        return list;
    }

    public static void main(String[] args) throws Exception {

         Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/gmall_marketing_0725?user=root&password=000000&useUnicode=true&characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");
        //Connection connection = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);

        List<JSONObject> list = queryList(connection,
                "select * from marketing_rule ",
                JSONObject.class,
                false);

        System.out.println(list);

        connection.close();

    }

}
